package bma.common.netty;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.jboss.netty.channel.group.ChannelGroup;

import bma.common.langutil.core.ObjectPair;
import bma.common.langutil.core.ObjectUtil;

public class NettySquare {

	protected static List<ObjectPair<String, ChannelGroup>> gathers = Collections
			.synchronizedList(new ArrayList<ObjectPair<String, ChannelGroup>>());

	public static void add(String name, ChannelGroup o) {
		if (o == null)
			return;
		if (name == null)
			name = "threadpool#" + System.identityHashCode(o);
		for (ObjectPair<String, ChannelGroup> op : gathers) {
			if (ObjectUtil.equals(op.getAttribute(), o)) {
				op.setValue(name);
				return;
			}
		}
		ObjectPair<String, ChannelGroup> op = new ObjectPair<String, ChannelGroup>(
				name, o);
		gathers.add(op);
	}

	public static void removeGroup(String name) {
		Object rm = null;
		for (ObjectPair<String, ChannelGroup> op : gathers) {
			if (ObjectUtil.equals(op.getValue(), name)) {
				rm = op;
				break;
			}
		}
		if (rm != null)
			gathers.remove(rm);
	}

	public static void remove(ChannelGroup o) {
		Object rm = null;
		for (ObjectPair<String, ChannelGroup> op : gathers) {
			if (ObjectUtil.equals(op.getAttribute(), o)) {
				rm = op;
				break;
			}
		}
		if (rm != null) {
			gathers.remove(rm);
		}
	}

	public static List<ObjectPair<String, ChannelGroup>> listGroup() {
		return new ArrayList<ObjectPair<String, ChannelGroup>>(gathers);
	}
}
